//
//  Validate.swift
//
//  Created by 薛永伟 on 2017/12/25.
//  Copyright © 2017年 Yuri. All rights reserved.
//

import Foundation

enum YRValidate {
    
    /// 邮箱
    case email(_: String)
    
    /// 手机号
    case phoneNum(_: String)
    
    /// q车牌号
    case carNum(_: String)
    
    /// 用户名
    case username(_: String)
    
    /// 密码
    case password(_: String)
    
    /// 昵称
    case nickname(_: String)
    
    /// URL
    case URL(_: String)
    
    /// IP地址
    case IP(_: String)
    
    /// 数字
    case number(_: String)
    
    /// 中文
    case chinses(_: String)
    
    /// 身份证
    case idcard(_: String)
    
    
    var isRight: Bool {
        
        var predicateStr:String!
        var currObject:String!
        
        switch self {
        case let .email(str):
            predicateStr = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
            currObject = str
        case let .phoneNum(str):
            predicateStr = "^1[3|4|5|7|8][0-9]{9}$"
            currObject = str
        case let .carNum(str):
            predicateStr = "^[A-Za-z]{1}[A-Za-z_0-9]{5}$"
            currObject = str
        case let .username(str):
            predicateStr = "^[A-Za-z0-9]{6,15}+$"
            currObject = str
        case let .password(str):
            predicateStr = "^[a-zA-Z0-9]{6,20}+$"
            currObject = str
        case let .nickname(str):
            predicateStr = "^[\\u4e00-\\u9fa5]{4,8}$"
            currObject = str
        case let .URL(str):
            predicateStr = "^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$"
            currObject = str
        case let .IP(str):
            predicateStr = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
            currObject = str
        case let .number(str):
            predicateStr = "^[0-9]*$"
            currObject = str
            
        case let .chinses(str):
            predicateStr = "^[\\u4e00-\\u9fa5]{1,5}$"
            currObject = str
            
        case let .idcard(str):
            predicateStr = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$"
            currObject = str
            
        }
        
        let predicate =  NSPredicate(format: "SELF MATCHES %@" ,predicateStr)
        return predicate.evaluate(with: currObject)
    }
}
